package org.zezi.loader.ui.fragment;

import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;

import org.zezi.loader.provider.ShopListContract;
import org.zezi.loader.provider.ShopListContract.Items;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;

public class LoaderTaskFragment extends Fragment {

	public static final String TAG = "LoaderTaskFragment";

	private static final String[] LIST = { "Milk", "Milk And Honey", "Apples", "Oranges", "Coffee", "Donuts",
			"Sweets", "Cheese", "Ham" };

	private AtomicBoolean mIsInserting = new AtomicBoolean(true);
	
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			
		};
	};

	private Runnable mTimer = new Runnable() {
		
		@Override
		public void run() {
			Log.v(TAG, "Executing database operation");
			ContentResolver cr = getActivity().getContentResolver();
			Random r = new Random();
			
			if (mIsInserting.get()) {
				mIsInserting.set(false);
				ContentValues values = new ContentValues();
				values.put(ShopListContract.Items.COLUMN_NAME_NAME, LIST[r.nextInt(LIST.length)]);
				values.put(ShopListContract.Items.COLUMN_NAME_COUNT, r.nextInt(5));
				cr.insert(ShopListContract.Items.CONTENT_URI, values);
				
				values = new ContentValues();
				values.put(ShopListContract.Items.COLUMN_NAME_NAME, LIST[r.nextInt(LIST.length)]);
				values.put(ShopListContract.Items.COLUMN_NAME_COUNT, r.nextInt(5));
				cr.insert(ShopListContract.Items.CONTENT_URI, values);
			} else {
				mIsInserting.set(true);
				Cursor c = cr.query(ShopListContract.Items.CONTENT_URI,
						new String[] { ShopListContract.Items._ID }, null, null, null);
				if (c.getCount() > 0) {
					int position = r.nextInt(c.getCount());
					c.moveToPosition(position);
					int id = c.getInt(c.getColumnIndexOrThrow(ShopListContract.Items._ID));
					String selection = Items._ID + "=?";
					String[] selectionArgs = {String.valueOf(id)};
					int deleted = cr.delete(Items.CONTENT_URI, selection, selectionArgs);
				}
			}
			
			

			mHandler.postDelayed(this, 6 * 1000);
		}
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRetainInstance(true);

		restart();
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		stop();
	}

	private void modifDatabase() {
		mHandler.postDelayed(mTimer, 3 * 1000);
	}
	
	private void restart() {
		modifDatabase();
	}
	
	private void stop() {
		mHandler.removeCallbacks(mTimer);
	}
}
